<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item label="消息标题" prop="title">
                        <el-input
                            v-model.trim="state.ruleForm.title"
                            clearable
                            placeholder="请输入消息标题"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="推送时间" prop="pushDatetime">
                        <el-date-picker
                            class="w-100%! max-w-340"
                            v-model="state.ruleForm.pushDatetime"
                            type="datetime"
                            placeholder="请选择推送时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            time-format="HH:mm:ss"
                            :disabled-date="disabledDate"
                            :disabled-hours="disabledHours"
                            :disabled-minutes="disabledMinutes"
                            :default-time="new Date(Date.now() + 60000)"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="消息状态" prop="state">
                        <el-select
                            v-model="state.ruleForm.state"
                            placeholder="请选择消息状态"
                            clearable
                        >
                            <el-option
                                v-for="item in state.messageStateList"
                                :key="item.memberKey"
                                :label="item.memberName"
                                :value="item.memberKey"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="8"
                    ><el-form-item label="类型" prop="type">
                        <el-select
                            v-model="state.ruleForm.type"
                            placeholder="请选择类型"
                        >
                            <el-option
                                v-for="item in state.messageTypeList"
                                :key="item.memberKey"
                                :label="item.memberName"
                                :value="item.memberKey"
                            />
                        </el-select> </el-form-item
                ></el-col>
                <el-col :span="8"
                    ><el-form-item label="备注" prop="note">
                        <el-input
                            v-model.trim="state.ruleForm.note"
                            type="textarea"
                            maxlength="100"
                            :autosize="{ minRows: 2 }"
                            clearable
                            show-word-limit
                            placeholder="请输入备注"
                        /> </el-form-item
                ></el-col>
                <el-col :span="8"
                    ><el-form-item label="状态" prop="status">
                        <el-radio-group v-model="state.ruleForm.status">
                            <el-radio
                                v-for="item in state.statusList"
                                :key="item.memberKey"
                                :value="item.memberKey"
                                >{{ item.memberName }}</el-radio
                            >
                        </el-radio-group>
                    </el-form-item></el-col
                >
            </el-row>

            <el-form-item label="消息内容" prop="message">
                <MyEditor v-model:value="state.ruleForm.message" />
            </el-form-item>
        </el-form>

        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="state.form_loading"
                @click="submitForm(ruleRef)"
            >
                {{ isEdit ? "修改" : "添加" }}
            </el-button>
        </div>
        <go-back />
    </div>
</template>

<script setup>
import { inject, ref, onMounted, reactive, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";
import { getMessageDetail, addMessage, editMessage } from "@/apis/message.js";
import MyEditor from "@/components/MyEditor.vue";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore
    .getDictMembers("enttp_message_reciever_type")
    .then(
        (res) =>
            (state.messageTypeList = res.filter(
                (item) => ![5, 6].includes(item.memberKey)
            ))
    );
dictStore
    .getDictMembers("message_state")
    .then(
        (res) =>
            (state.messageStateList = res.filter(
                (item) => item.memberKey !== 2
            ))
    );

const router = useRouter();
const route = useRoute();

const $message = inject("$message");

const sid = route.query.sid;
const isEdit = ref(false);
const form_loading = ref(false);
const ruleRef = ref(null);
const state = reactive({
    statusList: [],
    messageTypeList: [],
    messageStateList: [],
    ruleForm: {
        title: null,
        message: null,
        pushDatetime: null,
        type: null,
        note: null,
        state: null,
        status: 0,
    },
    rules: {
        title: [{ required: true, message: "请输入消息标题", trigger: "blur" }],
        message: [
            { required: true, message: "请输入消息内容", trigger: "blur" },
        ],
        pushDatetime: [
            { required: true, message: "请选择推送时间", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "blur" }],
    },
});

onMounted(() => {
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
        getDetail();
    }
});

const disabledDate = (time) => {
    return time.getTime() <= Date.now() - 1000 * 3600 * 24;
};

const makeRange = (start, end) => {
    const result = [];
    for (let i = start; i <= end; i++) {
        result.push(i);
    }
    return result;
};

// 是否选择今天
const isSelectedToday = computed(() => {
    const { pushDatetime } = state.ruleForm;
    if (!pushDatetime) return false;

    const pushDate = new Date(pushDatetime);
    const year = pushDate.getFullYear();
    const month = pushDate.getMonth();
    const day = pushDate.getDay();

    const date = new Date();
    const nowYear = date.getFullYear();
    const nowMonth = date.getMonth();
    const nowDay = date.getDay();
    if (year === nowYear && month === nowMonth && day === nowDay) {
        return true;
    } else {
        return false;
    }
});

const disabledHours = () => {
    // 同一天则禁用掉当前时间之前的所有时间
    if (isSelectedToday.value) {
        return makeRange(0, new Date().getHours() - 1);
    }
};

const disabledMinutes = () => {
    // 同一天则禁用掉当前时间之前的所有时间
    if (isSelectedToday.value) {
        return makeRange(0, new Date().getMinutes());
    }
};

const getDetail = async () => {
    const res = await getMessageDetail({ sid });
    if (res.data.code == 200) {
        state.ruleForm = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res = null;
            if (isEdit.value) {
                res = await editMessage(state.ruleForm);
            } else {
                res = await addMessage(state.ruleForm);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};
</script>
